<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    *{
     margin: 0;
     padding: 0;
    }
    #map{
      width: 800px;
      height: 600px;
      background-color: #ccc;
      position: relative;
    }
    #map div{
      position: absolute;
    }
  </style>
</head>
<body>
  <div id='score'>当前分数为：0分</div>
  <!-- 绘制地图 -->
  <div id='map'></div>
  <script>
    //准备食物的初始数据
    function Food(options){ 
      this.width = options.width || 20;
      this.height = options.height || 20;
      this.color = options.color || 'green';
      this.map = options.map;

    }
    //将食物绘制 添加到地图中 并显示出来
    Food.prototype.init = function(){
      //删除旧的食物盒子
      if(this.element){
        this.map.removeChild(this.element)
      }
      //创建新的食物盒子
      var div = document.createElement('div')
      this.element = div;
      div.style.width = this.width + 'px';
      div.style.height = this.height + 'px';
      div.style.backgroundColor = this.color;
      this.map.appendChild(div);

      this.randomPos();
    }
    //绘制食物的随机显示位置
    Food.prototype.randomPos = function(){
      //获取元素的随机显示位置（本身坐标）
      this.x = Math.floor(Math.random()*this.map.offsetWidth / this.width);
      this.y = Math.floor(Math.random()*this.map.offsetHeight / this.height);
    
      //获取元素的在页面中的位置（距离地图中的left和top值）
      this.element.style.left = this.x * this.width +'px';
      this.element.style.top = this.y * this.height +'px';
    }
    //准备小蛇初始数据
    function Snake(options){
      this.width = options.width || 20;
      this.height = options.height || 20;
      this.map = options.map;
      this.body =[
        {x:1,y:1,color:'orange'},
        {x:2,y:1,color:'orange'},
        {x:3,y:1,color:'red'},
      ];
      this.elements = [];
      this.fangxiang = 'right';
    }
    //将小蛇绘制出来 添加到地图上 并显示出来
    Snake.prototype.init =  function(){
      //删除旧蛇
      for(var i = 0 ; i < this.elements.length ; i++){
        this.map.removeChild(this.elements[i]);
      };
      this.elements = [];
      //创建新蛇
      var body = this.body;
      for(var i = 0; i < body.length; i++){
        var div = document.createElement('div');
        this.elements.push(div);
        div.style.width = this.width + 'px';
        div.style.height = this.height + 'px';
        div.style.backgroundColor = body[i].color;
        div.style.left = body[i].x * this.width +'px';
        div.style.top = body[i].y * this.height + 'px';
        this.map.appendChild(div)
      }
    }
    //绘制小蛇的移动功能
    Snake.prototype.move = function(){
     //console.log(this.fangxiang)
      //绘制蛇身（通过观察蛇身是全新坐标，蛇身是前一节的坐标）
      for(var i = 0 ; i < this.body.length-1 ; i++){
        this.body[i].x = this.body[i+1].x;
        this.body[i].y = this.body[i+1].y;
      }
      //绘制蛇头
      //this.body[this.body.length-1].x++;
      switch(this.fangxiang){
        case 'left':
          this.body[this.body.length-1].x--;
          break;
        case 'up':
          this.body[this.body.length-1].y--;
          break;
        case 'right':
          this.body[this.body.length-1].x++;
          break;
        case 'down':
          this.body[this.body.length-1].y++;
          break;
      }
    }
    //游戏功能控制（数据准备）
    function Game(mapDiv,score){
      this.food = new Food({map:mapDiv});
      this.snake = new Snake({map:mapDiv});
      this.map = mapDiv;
      this.score = score;
      
    }
    //启动游戏
    Game.prototype.start = function(){
      //启动绘制小蛇和绘制食物
      this.food.init();
      this.snake.init();
      //让小蛇运动的功能
      this.snakeRun();
      //使用按键控制小蛇
      this.changeDir()
    }
    //
    Game.prototype.snakeRun = function(){
      var snake = this.snake;
      var sheTou = snake.body[snake.body.length-1]
      var food = this.food;
      var that = this;
      var num = 0;
      var score = this.score;
      //通过定时器让小蛇跑起来
      var timeId = setInterval(function(){
        var sheWeiX = snake.body[0].x
        var sheWeiY = snake.body[0].y
  
        snake.move();
        that.isEat(function(){
          snake.body.unshift({x:sheWeiX,y:sheWeiY,color:'blue'})
          num ++;
          score.innerText='当前分数为:'+num*10+'分';
          food.init()
        });
        if(that.isGameOver()){
          alert('游戏结束')
          clearInterval(timeId);
          return;
        }
        
      //小蛇吃食物
      // if(sheTou.x === food.x && sheTou.y === food.y){
      //   snake.body.unshift({x:sheWeiX,y:sheWeiY,color:'blue'})
      //   food.init()
      // }
      //小蛇撞墙 游戏结束
      // if(sheTou.x < 0 || sheTou.x >39 || sheTou.y < 0 || sheTou.y > 29 ){
      //   alert('游戏结束');
      //   clearInterval(timeId);
      //   return;
      // }
      //小蛇撞自己 游戏结束
      // for(var i = 0 ; i<snake.body.length-4;i++){
      //   if(sheTou.x === snake.body[i].x && sheTou.y === snake.body[i].y){
      //   alert('游戏结束')
      //   clearInterval(timeId);
      //   return;
      //   }
      // }
      snake.init();
      },150)
    }
    //按键功能
    Game.prototype.changeDir = function(){
      var snake = this.snake
      var flag = true
      //通过onkeydow事件控制小蛇使用键盘 移动的方向
      document.onkeydown = function(e){
        if(!flag){
          return;
        }
        flag = false;
        setTimeout(function(){
          flag = true;
        },150)

        //console.log(e.keyCode)
        var keyCode = e.keyCode;
        switch(true){
          case keyCode === 37 && snake.fangxiang != 'right':
            snake.fangxiang = 'left';
            break;
          case keyCode ===38 && snake.fangxiang != 'down':
            snake.fangxiang = 'up';
            break;
          case keyCode ===39 && snake.fangxiang != 'left':
            snake.fangxiang ='right';
            break;
          case keyCode ===40 && snake.fangxiang != 'up':
            snake.fangxiang = 'down';
            break;
        }
      }
    }
    Game.prototype.isEat = function(fn){
      var snake = this.snake;
      var sheTou = snake.body[snake.body.length-1]
      var food = this.food;
      if(sheTou.x === food.x && sheTou.y === food.y){
        fn()
      }   
    }
    Game.prototype.isGameOver = function(){
      var snake = this.snake;
      var sheTou = snake.body[snake.body.length-1]
      if(sheTou.x < 0 || sheTou.x >39 || sheTou.y < 0 || sheTou.y > 29 ){
        return true;
      }
      //小蛇撞自己 游戏结束
      for(var i = 0 ; i<snake.body.length-4;i++){
        if(sheTou.x === snake.body[i].x && sheTou.y === snake.body[i].y){
        return true;
        }
      }
     return false;
    }
    var score = document.getElementById('score')
    var mapDiv = document.getElementById('map')
    var g1 = new Game(mapDiv,score);
    g1.start();
   

    // var s1 = new Snake({
    //   map:mapDiv,
    // })
    // s1.move()
  
    // var f1 = new Food({
    //   map:mapDiv,
    // })
    // f1.init();
    
    
  </script>
</body>
</html>